package com.pss.oauth2.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pss.oauth2.dao.UserMapper;
import com.pss.oauth2.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.security.core.authority.AuthorityUtils.createAuthorityList;

/**
 * 用户管理业务类
 */
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> uLqw = new LambdaQueryWrapper<>();
        uLqw.eq(User::getUsername, username);
        User securityUser = userMapper.selectOne(uLqw);
        String roles = securityUser.getRoles();
        if (org.apache.commons.lang.StringUtils.isNotBlank(roles)) {
            securityUser.setAuthorities(createAuthorityList(StringUtils.tokenizeToStringArray(roles, ",")));
        }
        if (!securityUser.isEnabled()) {
            throw new DisabledException("ACCOUNT_DISABLED");
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException("ACCOUNT_LOCKED");
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException("ACCOUNT_EXPIRED");
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException("CREDENTIALS_EXPIRED");
        }
        return securityUser;
    }

}
